import 'dart:ui';
import 'dart:math';

import 'package:animated_transitions/animated_transitions.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:gradient_borders/gradient_borders.dart';
import 'package:redux/redux.dart';
import 'package:vamos/view/publish/publish_page.dart';
import 'package:vamos/view/question/social_detail_page.dart';
import 'package:vamos/view/system/settings_page.dart';
import 'package:vamos/view/profile/edit_profile_page.dart';
import 'package:zo_animated_border/zo_animated_border.dart';
import '../../core/index.dart';
import '../system/auth_page.dart';
import '../../core/widgets/report_dialog.dart';
import '../../core/store/redux_visitor_manager.dart';
import 'visitor_records_page.dart';

/// 个人页面
class VamosProfileInterface extends StatefulWidget {
  const VamosProfileInterface({super.key});

  @override
  State<VamosProfileInterface> createState() => _VamosProfileInterfaceState();
}

class _VamosProfileInterfaceState extends State<VamosProfileInterface>
    with TickerProviderStateMixin {
  late TabController _tabController;
  int _selectedTabIndex = 0;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      setState(() {
        _selectedTabIndex = _tabController.index;
      });
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, AppState>(
      converter: (store) => store.state,
      builder: (context, state) {
        return Scaffold(
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my_background.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: _buildProfileContent(state),
          ).safeArea(top: false, bottom: false),
        );
      },
    );
  }

  Widget _buildProfileContent(AppState state) {
    final currentUser = state.userState.activeUser;

    if (currentUser == null) {
      return _buildLoginPrompt();
    }

    return _buildProfileInterface(currentUser);
  }

  /// 构建未登录提示
  Widget _buildLoginPrompt() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 项目Logo
        Container(
          width: 120.w,
          height: 120.w,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(34.r),
            image: const DecorationImage(
              image: AssetImage('assets/images/logo.png'),
              fit: BoxFit.cover,
            ),
          ),
        ).paddingBottom(32.h),

        // 提示信息
        Text(
          'Please login to access your profile',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18.sp,
            fontWeight: FontWeight.w500,
            fontFamily:
                GoogleFonts.poppins(fontWeight: FontWeight.w500).fontFamily,
          ),
          textAlign: TextAlign.center,
        ).paddingHorizontal(32.w).paddingBottom(24.h),

        // 前往登录按钮
        ZoAnimatedGradientBorder(
          borderRadius: 24.r,
          borderThickness: 2.0,
          gradientColor: const [
            Color(0xFF83BE4A),
            Color(0xFFF3E3C6),
            Color(0xFFFB894E),
          ],
          child: Container(
            width: 200.w,
            height: 48.h,
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.8),
              borderRadius: BorderRadius.circular(24.r),
            ),
            child: Text(
              'Go to Login',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w600).fontFamily,
              ),
            ).center().inkWell(
              onTap: () {
                Navigator.of(context).push(
                  TransitionPageRoute(
                    builder: (context) => UserAuthPage(),
                    transitionAnimation: DirectionalPixelatedTransition(
                      duration: const Duration(milliseconds: 600),
                      colors: [
                        Color(0xFF83BE4A),
                        Color(0xFFF3E3C6),
                        Color(0xFFFB894E),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
        ),
      ],
    );
  }

  /// 构建个人页面界面
  Widget _buildProfileInterface(UserDataEntity user) {
    return Stack(
      children: [
        SingleChildScrollView(
          child: Column(
            children: [
              // 状态栏占位
              SizedBox(height: MediaQuery.of(context).padding.top + 30.h),

              // 个人资料头部
              _buildProfileHeader(user),

              // Time Capsule 图片
              _buildTimeCapsuleImage(),

              // 内容标签页
              _buildContentTabs(),

              // 内容区域
              _buildContentArea(),

              // 底部间距
              SizedBox(height: 120.h),
            ],
          ),
        ),

        // 右上角设置按钮
        _buildSettingsButton(),
      ],
    );
  }

  /// 构建设置按钮
  Widget _buildSettingsButton() {
    return Positioned(
      top: MediaQuery.of(context).padding.top,
      right: 16.w,
      child: Container(
        width: 40.w,
        height: 40.w,
        decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.5),
          shape: BoxShape.circle,
        ),
        child: Image.asset(
          'assets/images/setting.png',
          width: 20.w,
          height: 20.w,
        ).center().inkWell(
          onTap: () {
            _navigateToSettings();
          },
        ),
      ),
    );
  }

  /// 跳转到设置页面
  void _navigateToSettings() {
    final store = StoreProvider.of<AppState>(context);
    Navigator.of(context).push(
      TransitionPageRoute(
        builder:
            (context) => StoreProvider<AppState>(
              store: store,
              child: const VamosSettingsInterface(),
            ),
        transitionAnimation: ClockSweepTransition(
          colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
        ),
      ),
    );
  }

  /// 跳转到编辑资料页面
  void _navigateToEditProfile() {
    final store = StoreProvider.of<AppState>(context);
    Navigator.of(context).push(
      TransitionPageRoute(
        builder:
            (context) => StoreProvider<AppState>(
              store: store,
              child: const VamosEditProfileInterface(),
            ),
        transitionAnimation: CrossingBarsTransition(
          direction: TransitionDirection.right,
          colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
        ),
      ),
    );
  }

  /// 构建个人资料头部
  Widget _buildProfileHeader(UserDataEntity user) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 20.h),
      child: Column(
        children: [
          // 头像和统计信息
          Row(
            children: [
              // 头像
              Container(
                width: 88.w,
                height: 88.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: GradientBoxBorder(
                    width: 2.w,
                    gradient: LinearGradient(
                      colors: [Color(0xFF83BE4A), Color(0xFFFB894E)],
                    ),
                  ),
                ),
                child: Container(
                  width: 80.w,
                  height: 80.w,
                  margin: EdgeInsets.all(4.w), // 边框和头像之间的间距
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: Colors.transparent,
                  ),
                  child: ClipOval(
                    child:
                        user.profileImage.isNotEmpty
                            ? Image.asset(
                              user.profileImage,
                              width: 76.w,
                              height: 76.w,
                              fit: BoxFit.cover,
                            )
                            : Icon(
                              Icons.person,
                              size: 40.w,
                              color: Colors.white,
                            ).center(),
                  ),
                ),
              ),

              SizedBox(width: 20.w),

              // 统计信息
              Expanded(
                child: StoreConnector<AppState, Map<String, int>>(
                  converter: (store) {
                    final currentUser = store.state.userState.activeUser;
                    if (currentUser == null) {
                      return {'followers': 0, 'following': 0, 'visitor': 0};
                    }

                    final followManager = serviceLocator<ReduxFollowManager>();
                    final visitorManager =
                        serviceLocator<ReduxVisitorManager>();
                    final followers = followManager.getFollowerCount(
                      currentUser.uniqueId,
                    );
                    final following = followManager.getFollowingCount(
                      currentUser.uniqueId,
                    );
                    final visitor = visitorManager.getVisitorCountForUser(
                      currentUser.uniqueId,
                    );

                    return {
                      'followers': followers,
                      'following': following,
                      'visitor': visitor,
                    };
                  },
                  builder: (context, stats) {
                    return Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildStatItem(
                          _formatCount(stats['followers']!),
                          'Followers',
                        ),
                        _buildVerticalDivider(),
                        _buildStatItem('', 'Visitor', isVisitor: true).inkWell(
                          onTap: () {
                            Navigator.push(
                              context,
                              TransitionPageRoute(
                                builder:
                                    (context) => StoreProvider<AppState>(
                                      store: serviceLocator<Store<AppState>>(),
                                      child: VamosVisitorRecordsInterface(),
                                    ),
                                transitionAnimation: BrushStrokeTransition(
                                  direction: TransitionDirection.right,
                                  colors: [
                                    Color(0xFF83BE4A),
                                    Color(0xFFF3E3C6),
                                    Color(0xFFFB894E),
                                  ],
                                ),
                              ),
                            );
                          },
                        ),
                        _buildVerticalDivider(),
                        _buildStatItem(
                          _formatCount(stats['following']!),
                          'Follow',
                        ),
                      ],
                    );
                  },
                ),
              ),
            ],
          ),

          SizedBox(height: 16.h),

          // 用户名和编辑按钮
          Row(
            children: [
              Text(
                user.displayName,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 24.sp,
                  fontWeight: FontWeight.w700,
                  fontFamily:
                      GoogleFonts.poppins(
                        fontWeight: FontWeight.w700,
                      ).fontFamily,
                ),
              ),
              Spacer(),
              ClipRRect(
                borderRadius: BorderRadius.circular(20.r),
                child: BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
                  child: Container(
                    width: 230.w,
                    padding: EdgeInsets.symmetric(
                      horizontal: 16.w,
                      vertical: 12.h,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(24.r),
                      border: GradientBoxBorder(
                        width: 1.w,
                        gradient: LinearGradient(
                          colors: [
                            Colors.white.withOpacity(0),
                            Colors.white.withOpacity(0.4),
                          ],
                        ),
                      ),
                    ),
                    child: Text(
                      'Edit Profile',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500,
                        fontFamily:
                            GoogleFonts.poppins(
                              fontWeight: FontWeight.w500,
                            ).fontFamily,
                      ),
                    ).center().inkWell(
                      onTap: () {
                        _navigateToEditProfile();
                      },
                    ),
                  ),
                ),
              ),
            ],
          ),

          SizedBox(height: 8.h),

          // 个人简介
          Text(
            user.personalBio.isNotEmpty
                ? user.personalBio
                : 'Deep skateboard enthusiasts, those who like it can join forces',
            style: TextStyle(
              color: Colors.white.withOpacity(0.7),
              fontSize: 14.sp,
              fontFamily:
                  GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建统计项
  Widget _buildStatItem(String value, String label, {bool isVisitor = false}) {
    return Column(
      children: [
        if (isVisitor)
          Image.asset(
            'assets/images/eye-view.png',
            width: 24.w,
            height: 24.w,
          ).paddingTop(2.w)
        else
          Text(
            value,
            style: TextStyle(
              color: Colors.white,
              fontSize: 18.sp,
              fontWeight: FontWeight.w500,
              fontFamily:
                  GoogleFonts.poppins(fontWeight: FontWeight.w500).fontFamily,
            ),
          ),
        SizedBox(height: 4.h),
        Text(
          label,
          style: TextStyle(
            color: Colors.white.withOpacity(0.6),
            fontSize: 12.sp,
            fontFamily:
                GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily,
          ),
        ),
      ],
    );
  }

  /// 构建竖线分割
  Widget _buildVerticalDivider() {
    return Container(
      width: 1.w,
      height: 20.h,
      color: Colors.white.withOpacity(0.3),
    ).paddingTop(3.w);
  }

  /// 构建Time Capsule图片
  Widget _buildTimeCapsuleImage() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 0.h),
      child: Image.asset(
        'assets/images/time_capsule.png',
        width: double.infinity,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            width: double.infinity,
            height: 120.h,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(12.r),
            ),
            child:
                Icon(Icons.image, color: Colors.grey[600], size: 40.w).center(),
          );
        },
      ).inkWell(
        onTap: () {
          Navigator.push(
            context,
            TransitionPageRoute(
              builder: (context) => VamosPublishInterface(initialTabIndex: 1),
              transitionAnimation: SunburstTransition(
                colors: [
                  Color(0xFF83BE4A),
                  Color(0xFFF3E3C6),
                  Color(0xFFFB894E),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  /// 构建内容标签页
  Widget _buildContentTabs() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          _buildTabButton('Release', 0),
          SizedBox(width: 24.w),
          _buildTabButton('Like', 1),
        ],
      ),
    );
  }

  /// 构建标签按钮
  Widget _buildTabButton(String title, int index) {
    final isSelected = _selectedTabIndex == index;
    return Text(
      title,
      style: TextStyle(
        color: isSelected ? Colors.white : Colors.white.withOpacity(0.5),
        fontSize: 20.sp,
        fontWeight: isSelected ? FontWeight.w700 : FontWeight.w400,
        fontFamily:
            GoogleFonts.nunito(
              fontWeight: isSelected ? FontWeight.w800 : FontWeight.w800,
            ).fontFamily,
      ),
    ).inkWell(
      onTap: () {
        setState(() {
          _selectedTabIndex = index;
        });
        _tabController.animateTo(index);
      },
    );
  }

  /// 构建内容区域
  Widget _buildContentArea() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: IndexedStack(
        index: _selectedTabIndex,
        children: [_buildReleaseContent(), _buildLikeContent()],
      ),
    );
  }

  /// 构建发布内容
  Widget _buildReleaseContent() {
    return StoreConnector<AppState, List<SocialPostEntity>>(
      converter: (store) {
        final currentUser = store.state.userState.activeUser;
        if (currentUser == null) return [];

        return store.state.socialState.postCollection
            .where((post) => post.authorId == currentUser.uniqueId)
            .toList();
      },
      builder: (context, userPosts) {
        if (userPosts.isEmpty) {
          return _buildEmptyState(
            'No posts yet',
            'Start sharing your moments!',
          );
        }

        return GridView.builder(
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            crossAxisSpacing: 12.w,
            mainAxisSpacing: 12.h,
            childAspectRatio: 157 / 250,
          ),
          itemCount: userPosts.length,
          itemBuilder: (context, index) {
            return _buildPostItem(userPosts[index]);
          },
        );
      },
    );
  }

  /// 构建点赞内容
  Widget _buildLikeContent() {
    return StoreConnector<AppState, List<SocialPostEntity>>(
      converter: (store) {
        final currentUser = store.state.userState.activeUser;
        if (currentUser == null) return [];

        return store.state.socialState.postCollection
            .where((post) => post.likedUserIds.contains(currentUser.uniqueId))
            .toList();
      },
      builder: (context, likedPosts) {
        if (likedPosts.isEmpty) {
          return _buildEmptyState(
            'No liked posts',
            'Like posts to see them here!',
          );
        }

        return GridView.builder(
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            crossAxisSpacing: 12.w,
            mainAxisSpacing: 12.h,
            childAspectRatio: 157 / 250,
          ),
          itemCount: likedPosts.length,
          itemBuilder: (context, index) {
            return _buildPostItem(likedPosts[index]);
          },
        );
      },
    );
  }

  /// 构建单个帖子项
  Widget _buildPostItem(SocialPostEntity post) {
    final isImage =
        post.mediaType == PostMediaType.image && post.mediaUrl != null;
    final isVideo =
        post.mediaType == PostMediaType.video && post.thumbnailUrl != null;
    final viewCount = _getFixedViewCount(post.postId); // 基于ID的固定浏览次数

    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        color: Colors.white.withOpacity(0.1),
        border: Border.all(color: Colors.white.withOpacity(0.2), width: 1),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 图片/视频区域
          Expanded(
            flex: 4,
            child: Padding(
              padding: EdgeInsets.all(5.w),
              child: Stack(
                children: [
                  // 媒体内容
                  Container(
                    width: double.infinity,
                    height: double.infinity,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(12.r),
                        topRight: Radius.circular(12.r),
                      ),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(12.r),
                        topRight: Radius.circular(12.r),
                      ),
                      child:
                          isImage
                              ? Image.asset(
                                post.mediaUrl!,
                                width: double.infinity,
                                height: double.infinity,
                                fit: BoxFit.cover,
                                errorBuilder: (context, error, stackTrace) {
                                  return Container(
                                    color: Colors.grey[800],
                                    child:
                                        Icon(
                                          Icons.image,
                                          size: 32.w,
                                          color: Colors.grey[600],
                                        ).center(),
                                  );
                                },
                              )
                              : isVideo
                              ? Image.asset(
                                post.thumbnailUrl!,
                                width: double.infinity,
                                height: double.infinity,
                                fit: BoxFit.cover,
                                errorBuilder: (context, error, stackTrace) {
                                  return Container(
                                    color: Colors.grey[800],
                                    child:
                                        Icon(
                                          Icons.video_library,
                                          size: 32.w,
                                          color: Colors.grey[600],
                                        ).center(),
                                  );
                                },
                              )
                              : Container(
                                color: Colors.grey[800],
                                child:
                                    Icon(
                                      Icons.image,
                                      size: 32.w,
                                      color: Colors.grey[600],
                                    ).center(),
                              ),
                    ),
                  ),

                  // 视频播放图标
                  if (post.mediaType == PostMediaType.video)
                    SizedBox(
                      width: double.infinity,
                      height: double.infinity,
                      child:
                          Icon(
                            Icons.play_circle_filled,
                            size: 40.w,
                            color: Colors.white.withOpacity(0.9),
                          ).center(),
                    ),

                  // 右上角举报按钮
                  Positioned(
                    top: 8.h,
                    right: 8.w,
                    child: Container(
                      width: 24.w,
                      height: 24.w,
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.3),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.more_vert,
                        size: 16.w,
                        color: Colors.white,
                      ).center().inkWell(
                        onTap: () {
                          _handlePostReport(post);
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),

          // 文字信息区域
          Expanded(
            flex: 2,
            child: Padding(
              padding: EdgeInsets.all(8.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 动态文字（最多两行）
                  Expanded(
                    child: Text(
                      post.content,
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.white,
                        fontFamily:
                            GoogleFonts.poppins(
                              fontWeight: FontWeight.w400,
                            ).fontFamily,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),

                  SizedBox(height: 8.h),

                  // 时间和浏览次数
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // 时间
                      Text(
                        _formatPostTime(post.publishTime),
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.white.withOpacity(0.7),
                          fontFamily:
                              GoogleFonts.poppins(
                                fontWeight: FontWeight.w400,
                              ).fontFamily,
                        ),
                      ),

                      // 浏览次数
                      Row(
                        children: [
                          Image.asset(
                            'assets/images/eye.png',
                            width: 16.w,
                            height: 16.w,
                          ),
                          SizedBox(width: 4.w),
                          Text(
                            '$viewCount',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: Colors.white.withOpacity(0.7),
                              fontFamily:
                                  GoogleFonts.poppins(
                                    fontWeight: FontWeight.w400,
                                  ).fontFamily,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    ).inkWell(
      onTap: () {
        _handlePostTap(post);
      },
    );
  }

  /// 处理帖子点击
  void _handlePostTap(SocialPostEntity post) {
    // 检查登录状态
    final store = StoreProvider.of<AppState>(context);
    final currentUser = store.state.userState.activeUser;

    if (currentUser == null) {
      VamosLoginRequiredDialog.showLoginRequiredDialog(context);
      return;
    }

    // 跳转到帖子详情页面
    Navigator.of(context).push(
      TransitionPageRoute(
        builder: (context) => VamosSocialDetailInterface(post: post),
        transitionAnimation: BrushStrokeTransition(
          direction: TransitionDirection.right,
          colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
        ),
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState(String title, String subtitle) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 60.h),
      child: Column(
        children: [
          Image.asset(
            'assets/images/empty.png',
            width: 80.w,
            height: 80.w,
            fit: BoxFit.contain,
          ),
          SizedBox(height: 16.h),
          Text(title)
              .fontSize(16.sp)
              .textColor(Colors.white.withOpacity(0.7))
              .fontFamily(
                GoogleFonts.poppins(fontWeight: FontWeight.w500).fontFamily!,
              ),
          SizedBox(height: 8.h),
          Text(subtitle)
              .fontSize(14.sp)
              .textColor(Colors.white.withOpacity(0.5))
              .fontFamily(
                GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily!,
              ),
        ],
      ),
    );
  }

  /// 格式化发布时间
  String _formatPostTime(DateTime publishTime) {
    final hour = publishTime.hour.toString().padLeft(2, '0');
    final minute = publishTime.minute.toString().padLeft(2, '0');
    return '$hour:$minute';
  }

  /// 获取固定的浏览次数（基于ID生成）
  int _getFixedViewCount(String postId) {
    // 使用postId的hashCode来生成固定的随机数
    final random = Random(postId.hashCode);
    return random.nextInt(500) + 50; // 50-549之间的固定值
  }

  /// 格式化数字显示
  String _formatCount(int count) {
    if (count >= 1000000) {
      return '${(count / 1000000).toStringAsFixed(1)}M';
    } else if (count >= 1000) {
      return '${(count / 1000).toStringAsFixed(1)}K';
    } else {
      return count.toString();
    }
  }

  /// 处理帖子举报
  void _handlePostReport(SocialPostEntity post) {
    showVamosReportDialog(
      context: context,
      title: 'Report Post',
      subtitle: 'Please select a reason for reporting this post.',
      onReportSubmitted: (VamosReportOption option) {
        _deletePostAndExit(post);
      },
    );
  }

  /// 删除动态并返回
  void _deletePostAndExit(SocialPostEntity post) async {
    try {
      final socialManager = serviceLocator<ReduxSocialManager>();
      final success = await socialManager.deletePost(post.postId);
      if (success) {
        NotificationUtils.showSuccess(
          context,
          message: 'You won\'t see this again.',
        );
        // 不需要返回，因为列表会自动更新
      } else {
        NotificationUtils.showError(context, message: 'Failed to report post.');
      }
    } catch (e) {
      NotificationUtils.showError(context, message: 'Error reporting post: $e');
    }
  }
}
